<template>
	<div class="login">
		<el-form
			ref="loginRef"
			:model="loginForm"
			:rules="loginRules"
			class="login-form"
		>
			<h3 class="title">{{ title }}</h3>

			<!-- 切换登录方式 -->
			<div class="login-type-switch">
				<el-button
					type="text"
					@click="switchLoginType('account')"
					:class="{ active: loginType === 'account' }"
				>
					账号登录
				</el-button>
				<el-divider direction="vertical" />
				<el-button
					type="text"
					@click="switchLoginType('sms')"
					:class="{ active: loginType === 'sms' }"
				>
					手机号登录
				</el-button>
			</div>

			<!-- 账号登录表单 -->
			<div v-if="loginType === 'account'">
				<el-form-item prop="username">
					<el-input
						v-model="loginForm.username"
						type="text"
						size="large"
						auto-complete="off"
						placeholder="账号"
					>
						<template #prefix>
							<svg-icon icon-class="user" class="el-input__icon input-icon" />
						</template>
					</el-input>
				</el-form-item>
				<el-form-item prop="password">
					<el-input
						v-model="loginForm.password"
						type="password"
						size="large"
						auto-complete="off"
						placeholder="密码"
						@keyup.enter="handleLogin"
					>
						<template #prefix>
							<svg-icon
								icon-class="password"
								class="el-input__icon input-icon"
							/>
						</template>
					</el-input>
				</el-form-item>
				<!-- <el-form-item prop="code" v-if="captchaEnabled">
					<el-input
						v-model="loginForm.code"
						size="large"
						auto-complete="off"
						placeholder="验证码"
						style="width: 63%"
						@keyup.enter="handleLogin"
					>
						<template #prefix>
							<svg-icon
								icon-class="validCode"
								class="el-input__icon input-icon"
							/>
						</template>
					</el-input>
					<div class="login-code">
						<img :src="codeUrl" @click="getCode" class="login-code-img" />
					</div>
				</el-form-item> -->
				<el-checkbox
					v-model="loginForm.rememberMe"
					style="margin: 0px 0px 25px 0px"
				>
					记住密码
				</el-checkbox>
			</div>

			<!-- 手机号登录表单 -->
			<div v-else>
				<el-form-item prop="phone">
					<el-input
						v-model="loginForm.phone"
						type="text"
						size="large"
						autocomplete="off"
						placeholder="请输入手机号"
					>
						<template #prefix>
							<svg-icon icon-class="mobile" class="el-input__icon input-icon" />
						</template>
					</el-input>
				</el-form-item>
				<el-form-item prop="smsCode" style="position: relative">
					<el-input
						v-model="loginForm.smsCode"
						type="text"
						size="large"
						autocomplete="off"
						placeholder="请输入短信验证码"
						@keyup.enter="handleLogin"
					>
						<template #prefix>
							<svg-icon
								icon-class="validCode"
								class="el-input__icon input-icon"
							/>
						</template>
					</el-input>
					<el-button
						:disabled="smsCodeLoading || countdown > 0 || !loginForm.phone"
						@click="sendSmsCode"
						size="mini"
						style="
							position: absolute;
							right: 0;
							top: 0;
							height: 40px;
							padding: 0 12px;
						"
					>
						<span v-if="countdown === 0">获取验证码</span>
						<span v-else>{{ countdown }} 秒后重新获取</span>
					</el-button>
				</el-form-item>
			</div>

			<el-form-item style="width: 100%">
				<el-button
					:loading="loading"
					size="large"
					type="primary"
					style="width: 100%"
					@click.prevent="handleLogin"
				>
					<span v-if="!loading">登 录</span>
					<span v-else>登 录 中...</span>
				</el-button>
				<div style="float: right" v-if="register && loginType === 'account'">
					<router-link class="link-type" :to="'/register'"
						>立即注册</router-link
					>
				</div>
			</el-form-item>
		</el-form>

		<!-- 底部 -->
		<div class="el-login-footer">
			<div class="footer-content">
				<span>Copyright © 2025 chenjieyuan All Rights Reserved.</span>
				<span class="divider">|</span>
				<a href="https://beian.miit.gov.cn/" target="_blank" rel="noopener noreferrer" class="beian-link">
					粤ICP备2025443059号-1
				</a>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, reactive, watch, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getCodeImg, getSmsCode } from '@/api/login';
import Cookies from 'js-cookie';
import { encrypt, decrypt } from '@/utils/jsencrypt';
import useUserStore from '@/store/modules/user';

const title = import.meta.env.VITE_APP_TITLE;
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

// 登录类型：account-账号登录，sms-短信登录
const loginType = ref('account');

// 表单数据
const loginForm = reactive({
	username: 'admin',
	password: 'admin123',
	rememberMe: false,
	// code: '',
	uuid: '',
	phone: '',
	smsCode: '',
});

// 表单校验规则
const loginRules = {
	username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
	password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
	// code: [{ required: true, trigger: 'change', message: '请输入验证码' }],
	phone: [
		{ required: true, message: '请输入手机号', trigger: 'blur' },
		{
			pattern: /^1[3-9]\d{9}$/,
			message: '请输入有效的手机号',
			trigger: 'blur',
		},
	],
	smsCode: [{ required: true, message: '请输入短信验证码', trigger: 'blur' }],
};

const codeUrl = ref('');
const loading = ref(false);
const smsCodeLoading = ref(false);
const countdown = ref(0);
let countdownTimer = null;
const captchaEnabled = ref(true);
const register = ref(false);
const redirect = ref(undefined);

// 切换登录方式
function switchLoginType(type) {
	loginType.value = type;
	proxy.$refs.loginRef.clearValidate();
}

// 发送短信验证码
async function sendSmsCode() {
	if (!loginForm.phone) {
		ElMessage.warning('请输入手机号');
		return;
	}
	smsCodeLoading.value = true;
	try {
		await getSmsCode(loginForm.phone);
		ElMessage.success('验证码已发送，请注意查收');
		startCountdown();
	} catch (error) {
		ElMessage.error(error.message || '发送验证码失败');
	} finally {
		smsCodeLoading.value = false;
	}
}

// 开始倒计时
function startCountdown() {
	countdown.value = 60;
	countdownTimer = setInterval(() => {
		countdown.value--;
		if (countdown.value <= 0) {
			clearInterval(countdownTimer);
		}
	}, 1000);
}

// 获取图形验证码
function getCode() {
	getCodeImg().then(res => {
		captchaEnabled.value =
			res.captchaEnabled === undefined ? true : res.captchaEnabled;
		if (captchaEnabled.value) {
			codeUrl.value = 'data:image/gif;base64,' + res.img;
			loginForm.uuid = res.uuid;
		}
	});
}

// 处理登录
function handleLogin() {
	proxy.$refs.loginRef.validate(valid => {
		if (!valid) return;

		loading.value = true;

		if (loginType.value === 'account') {
			// 账号密码登录
			if (loginForm.rememberMe) {
				Cookies.set('username', loginForm.username, { expires: 30 });
				Cookies.set('password', encrypt(loginForm.password), { expires: 30 });
				Cookies.set('rememberMe', loginForm.rememberMe, { expires: 30 });
			} else {
				Cookies.remove('username');
				Cookies.remove('password');
				Cookies.remove('rememberMe');
			}

			userStore
				.login(loginForm)
				.then(() => {
					const query = route.query;
					const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
						if (cur !== 'redirect') acc[cur] = query[cur];
						return acc;
					}, {});
					router.push({ path: redirect.value || '/', query: otherQueryParams });
				})
				.catch(() => {
					loading.value = false;
					// if (captchaEnabled.value) getCode();
				});
		} else {
			// 短信验证码登录
			userStore
				.smsLogin({
					phone: loginForm.phone,
					code: loginForm.smsCode,
				})
				.then(() => {
					const query = route.query;
					const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
						if (cur !== 'redirect') acc[cur] = query[cur];
						return acc;
					}, {});
					router.push({ path: redirect.value || '/', query: otherQueryParams });
				})
				.catch(error => {
					ElMessage.error(error.message || '登录失败');
					loading.value = false;
				});
		}
	});
}

// 从cookie获取记住的账号密码
function getCookie() {
	const username = Cookies.get('username');
	const password = Cookies.get('password');
	const rememberMe = Cookies.get('rememberMe');
	loginForm.username = username === undefined ? loginForm.username : username;
	loginForm.password =
		password === undefined ? loginForm.password : decrypt(password);
	loginForm.rememberMe = rememberMe === undefined ? false : Boolean(rememberMe);
}

// 监听路由变化
watch(
	route,
	newRoute => {
		redirect.value = newRoute.query && newRoute.query.redirect;
	},
	{ immediate: true }
);

// 组件卸载时清除定时器
onUnmounted(() => {
	if (countdownTimer) clearInterval(countdownTimer);
});

// 初始化
// getCode();
getCookie();
</script>

<style lang="scss" scoped>
.login {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100%;
	background-image: url('../assets/images/login-background.jpg');
	background-size: cover;
}

.title {
	margin: 0px auto 30px auto;
	text-align: center;
	color: #707070;
}

.login-form {
	border-radius: 6px;
	background: #ffffff;
	width: 400px;
	padding: 25px 25px 5px 25px;
	z-index: 1;

	.el-input {
		height: 40px;
		input {
			height: 40px;
		}
	}

	.input-icon {
		height: 39px;
		width: 14px;
		margin-left: 0px;
	}
}

.login-type-switch {
	display: flex;
	justify-content: center;
	align-items: center;
	margin-bottom: 20px;

	.el-button {
		padding: 0 15px;
		color: #999;

		&.active {
			color: #409eff;
			font-weight: bold;
		}
	}

	.el-divider {
		margin: 0;
	}
}

.login-tip {
	font-size: 13px;
	text-align: center;
	color: #bfbfbf;
}

.login-code {
	width: 33%;
	height: 40px;
	float: right;

	img {
		cursor: pointer;
		vertical-align: middle;
	}
}

.el-login-footer {
	height: 40px;
	line-height: 40px;
	position: fixed;
	bottom: 0;
	width: 100%;
	text-align: center;
	color: #fff;
	font-family: Arial;
	font-size: 12px;
	letter-spacing: 1px;

	.footer-content {
		.divider {
			margin: 0 8px;
		}

		.beian-link {
			color: #fff;
			text-decoration: none;
			transition: color 0.3s;

			&:hover {
				color: #409eff;
				text-decoration: underline;
			}
		}
	}
}

.login-code-img {
	height: 40px;
	padding-left: 12px;
}

.link-type {
	color: #999;
	text-decoration: none;

	&:hover {
		color: #409eff;
	}
}
</style>
